#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
环境诊断脚本 - 帮助排查启动问题
"""

import os
import sys
import json
import subprocess
import importlib.util
from pathlib import Path

def check_python_environment():
    """检查Python环境"""
    print("🐍 Python环境检查")
    print(f"   Python版本: {sys.version}")
    print(f"   Python路径: {sys.executable}")
    print(f"   工作目录: {os.getcwd()}")
    
    # 检查虚拟环境
    venv_path = Path("venv")
    if venv_path.exists():
        print(f"   虚拟环境: 存在 ({venv_path.absolute()})")
        activate_script = venv_path / "bin" / "activate"
        if activate_script.exists():
            print(f"   激活脚本: 存在")
        else:
            print(f"   激活脚本: ❌ 不存在")
    else:
        print(f"   虚拟环境: ❌ 不存在")

def check_dependencies():
    """检查依赖包"""
    print("\n📦 依赖包检查")
    
    required_packages = [
        'flask', 'flask_cors', 'selenium', 'beautifulsoup4', 
        'requests', 'webdriver_manager'
    ]
    
    for package in required_packages:
        try:
            spec = importlib.util.find_spec(package)
            if spec is not None:
                print(f"   ✅ {package}: 已安装")
            else:
                print(f"   ❌ {package}: 未安装")
        except ImportError:
            print(f"   ❌ {package}: 导入失败")

def check_config_file():
    """检查配置文件"""
    print("\n📄 配置文件检查")
    
    config_file = Path("config.json")
    if config_file.exists():
        print(f"   配置文件: 存在")
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
            print(f"   ✅ JSON格式: 有效")
            print(f"   房间ID: {config.get('room_id', '未配置')}")
            print(f"   房间URL: {config.get('room_url', '未配置')}")
            print(f"   Webhook: {'启用' if config.get('webhook_enabled') else '禁用'}")
        except json.JSONDecodeError as e:
            print(f"   ❌ JSON格式: 无效 - {e}")
        except Exception as e:
            print(f"   ❌ 读取失败: {e}")
    else:
        print(f"   ❌ 配置文件: 不存在")

def check_chrome_driver():
    """检查Chrome和ChromeDriver"""
    print("\n🌐 Chrome/ChromeDriver检查")
    
    # 检查Chrome浏览器
    chrome_paths = [
        '/usr/bin/google-chrome',
        '/usr/bin/chromium-browser',
        '/usr/bin/chromium',
        '/snap/bin/chromium'
    ]
    
    chrome_found = False
    for path in chrome_paths:
        if Path(path).exists():
            print(f"   ✅ Chrome: 找到 ({path})")
            chrome_found = True
            break
    
    if not chrome_found:
        print(f"   ❌ Chrome: 未找到")
    
    # 检查ChromeDriver
    driver_paths = [
        '/usr/bin/chromedriver',
        '/usr/local/bin/chromedriver',
        '/snap/bin/chromium.chromedriver',
        '/home/lc/.local/bin/chromedriver'
    ]
    
    driver_found = False
    for path in driver_paths:
        if Path(path).exists():
            print(f"   ✅ ChromeDriver: 找到 ({path})")
            driver_found = True
            break
    
    if not driver_found:
        print(f"   ❌ ChromeDriver: 未找到")

def check_processes():
    """检查运行中的进程"""
    print("\n🔄 进程检查")
    
    try:
        # 检查Python进程
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        processes = result.stdout
        
        python_processes = [line for line in processes.split('\n') if 'python' in line and 'app.py' in line]
        if python_processes:
            print(f"   运行中的Python进程:")
            for process in python_processes:
                print(f"     {process.strip()}")
        else:
            print(f"   ❌ 没有找到运行中的app.py进程")
        
        # 检查端口占用
        result = subprocess.run(['lsof', '-i', ':5000'], capture_output=True, text=True)
        if result.returncode == 0 and result.stdout.strip():
            print(f"   ✅ 端口5000: 被占用")
            print(f"     {result.stdout.strip()}")
        else:
            print(f"   ❌ 端口5000: 未被占用")
            
    except Exception as e:
        print(f"   ❌ 进程检查失败: {e}")

def check_logs():
    """检查日志文件"""
    print("\n📋 日志检查")
    
    log_files = [
        "live_monitor.log",
        "logs/api.log",
        "logs/app.log"
    ]
    
    for log_file in log_files:
        path = Path(log_file)
        if path.exists():
            print(f"   ✅ {log_file}: 存在 ({path.stat().st_size} bytes)")
            # 显示最后几行
            try:
                with open(path, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                    if lines:
                        print(f"     最后几行:")
                        for line in lines[-3:]:
                            print(f"       {line.strip()}")
            except Exception as e:
                print(f"     读取失败: {e}")
        else:
            print(f"   ❌ {log_file}: 不存在")

def run_test_import():
    """测试导入主要模块"""
    print("\n🧪 模块导入测试")
    
    try:
        import app
        print("   ✅ app.py: 导入成功")
        
        # 测试配置管理器
        config_manager = app.ConfigManager()
        config = config_manager.get_config()
        print(f"   ✅ 配置管理器: 正常")
        
    except Exception as e:
        print(f"   ❌ 模块导入失败: {e}")

def main():
    """主函数"""
    print("=" * 60)
    print("🔍 直播间问题采集工具 - 环境诊断")
    print("=" * 60)
    
    check_python_environment()
    check_dependencies()
    check_config_file()
    check_chrome_driver()
    check_processes()
    check_logs()
    run_test_import()
    
    print("\n" + "=" * 60)
    print("💡 诊断完成")
    print("=" * 60)
    
    print("\n🔧 常见问题解决方案:")
    print("1. 配置文件JSON格式错误 → 修复config.json语法")
    print("2. 虚拟环境问题 → 重新创建: python3 -m venv venv")
    print("3. 依赖包缺失 → 安装依赖: pip install -r requirements.txt")
    print("4. Chrome/ChromeDriver缺失 → 安装浏览器和驱动")
    print("5. 端口被占用 → 停止其他进程或更换端口")

if __name__ == "__main__":
    main()